var com = new CommonUtil();
$(function(){
	var Order =  {
		basePath:com.basePath(),
		formSubmit:true,// 防止重复提交
		valids:{"cn":/^[\u4E00-\u9FA5]{1,6}$/,"number": /^[0-9]*[1-9][0-9]*$/,"tel":/^1[3456789]\d{9}$/,"phone":/^(?:(?:0\d{2,3}))?(?:\d{7,8})(-(?:\d{3,}))?$/},
		goods:["医疗器械","备品","其他"],
		goodsTypes:{"医疗器械":"1","备品":"2","其他":"0"},
		sendData:{},
		receiveData:{},
		sendName:"",
		sendPhone:"",
		uploader:null,
		pics:null,
		delImage:"",
		delId:"",
		delName:"",
		bindClick:function() {
			var o = this;
			o.pics = [];
			// 弹窗
			$(".ryp").click(function () {
				$(".cancel,.cxl").removeClass("ishidden");
			});
			$("#subBtn").click(function () {
				o.saveData();
			});
			// 选择框
			$("input[type=checkbox]").change(function () {
				var id = $(this).attr("id");
				if(id!=undefined && id.indexOf("Use")!=-1){
					if(id=="isUse" && $(this).prop('checked')){
						$(this).parent().find("#unUse").prop("checked",false).val("0");
					} else if(id=="unUse" && $(this).prop('checked')) {
						$(this).parent().find("#isUse").prop("checked",false).val("0");
					}
					$(this).val($(this).prop('checked') == true? "1" : "0");
					$("#useCar").val($("#isUse").val());
					$("#wholeOrder").val($("#isWholeOrder").val());
				} else  if(id.indexOf("Order")!=-1){
					if(id=="isWholeOrder" && $(this).prop('checked')){
						$(this).parent().find("#unWholeOrder").prop("checked",false).val("0");
					} else if(id=="unWholeOrder" && $(this).prop('checked')) {
						$(this).parent().find("#isWholeOrder").prop("checked",false).val("0");
					}
					$(this).val($(this).prop('checked') == true? "1" : "0");
					$("#wholeOrder").val($("#isWholeOrder").val()=="on"?"1":$("#isWholeOrder").val());
				} else {
					$(this).val($(this).prop('checked') == true? "1" : "0");
				}
			});
			// 编辑的赋值
			if($("#useCar").val()=="1"){
				$("#isUse").prop("checked",true).parent().find("#unUse").prop("checked",false);
			} else {
				$("#unUse").prop("checked",true).parent().find("#isUse").prop("checked",false);
			}
			if($("#wholeOrder").val()=="1"){
				$("#isWholeOrder").prop("checked",true).parent().find("#unWholeOrder").prop("checked",false);
			} else {
				$("#unWholeOrder").prop("checked",true).parent().find("#isWholeOrder").prop("checked",false);
			}

			// 物品选择
			$("#ryp").click(function () {
				o.createPicker($("#goodsType"),o.goods,$(this));
			});
			var goodsId = $("#goodsType").val();
			if(goodsId!=""){
				$("#ryp").find("label").text(goodsId=="0"?"其他":o.goods[parseInt(goodsId)-1]);
			}
			// 加载常用寄件地址
			o.ajaxRequst("getAddressList", "get", {type:"0"}, o.loadSendData);
			// 加载常用地址
			o.ajaxRequst("getAddressList", "get", {type:"1"}, o.loadReceiveData);
			if(!com.isMobileByAndroid()){
				//获取当前的top
				var top = $('body').scrollTop();
				//修复ios 软键盘关闭时input 移位问题
				$("#sendCompany").on("blur",function(){
					window.scroll(0,top);
				});
			}
			// 增加时间控件
			$("#receiveDate").click(function () {
				o.createDatePicker($(this));
			});
			// 增加删除地址事件
			$("img[id='dela']").click(function () {
				var dataid = $(this).attr("dataid");
				if(dataid != undefined && dataid !=null){
					o.ajaxRequst("delAddress","get",{id:dataid},o.cancelAddress);
				}
				o.delId = dataid;
				o.delName =$("input[name='sendCompany']").val();
				$(this).attr("dataid","");
				delete o.sendData[dataid];
			});
		},
		createDatePicker:function(obj){
			var params = {
				//value: com.isNull($("#registerDate").val()) ? [(minDate+1),'01','01'] : $("#registerDate").val().split("-"),
				format: "yyyy年mm月dd日 hh:ii",
				//minDate: minDate,
				//maxDate: maxDate,
				maxDateTime:com.addDate(new Date(),0),
				onSelectCallback: function (picker) {
					var value = com.isNull(picker.value) ? [picker.params.value] : picker.value;
					var now = new Date();
					var second = now.getSeconds() > 9 ? now.getSeconds() : "0" + now.getSeconds();
					// obj.val(com.dateFormat(value,"yyyy年MM月dd日 hh:mm:ss"));
					var arr = value.join("-").split("-");
					console.log("当前val:"+value);
					var temp = "";
					if(arr.length ==1 ){
						var arra1 = arr[0].split(",");
						temp = arra1[0]+"-"+arra1[1]+"-"+arra1[2]+" "+arra1[3]+":"+arra1[4];
					} else {
						if(com.isNull(arr[4])){
							arr[4] = "00";
						}
						temp = arr[0]+"-"+arr[1]+"-"+arr[2]+" "+arr[3]+":"+arr[4];
					}
					console.log(temp);
					obj.val(temp+":"+second);
					// obj.val(com.formatDate(value));
					picker.close();
				}
			}
			var datePic = new DatetimePicker(params);
			datePic.open();
		},
		eachDel:function (name,data){
			if(!com.isNull(name)){
				$.each(data,function (ind,d) {
					if(name == d){
						data.splice(ind,1);
					}
				});
			}
		},
		createPicker:function(obj,vals,other,disVals){
			Order.eachDel(Order.delId,vals);
			Order.eachDel(Order.delName,disVals);
			var pic = new Picker({
				cols: [{
					values: vals==null?disVals:vals,
					displayValues: disVals
				}],
				overlayCloseAble: true,
				onSelectCallback: function (picker) {
					// 物品选择
					if(other!=undefined && obj.attr("id")=="goodsType"){
						other.html("<label style='margin-right: 12%;'>" + picker.displayValue + "</label>");
						obj.val(Order.goodsTypes[picker.value]);
					} else {
						if(obj.attr("id")=="sendCompany"){
							// 根据选择动态填写上姓名，手机
							if(picker.value !=null && picker.value!=undefined){
								$("input[name='sendName']").val(Order.sendData[picker.value]["name"]);
								$("input[name='sendPhone']").val(Order.sendData[picker.value]["phone"]);
								$("input[name='sendCompany']").val(picker.displayValue);
								// 添加叉号删除不需要的地址
								if(obj.attr("id")=="sendCompany"){
									$("#dela").attr("dataid",Order.sendData[picker.value]["id"]);
									// return data.address + dela.prop("outerHTML");
								}
								// obj.val();
								Order.sendName = $("input[name='sendName']").val();
								Order.sendPhone = $("input[name='sendPhone']").val();
							}
						} else if(obj.attr("class")!=undefined && (obj.attr("class").indexOf("recPhone")!=-1 || obj.attr("class").indexOf("recName")!=-1
						|| obj.attr("class").indexOf("receiveAddress")!=-1 )){
							Order.loadRecAddress(picker.value[0]);
							$("#receiveId").val(picker.value)
							obj.val(picker.displayValue);
						} else {
							obj.val(picker.displayValue);
						}
					}
					picker.close();
				}
			});
			//if(curreId!="" || curreName!=""){
			// var cols = [{values:vals==null?disVals:vals, displayValues:disVals==undefined?vals:disVals}];
			// cols[0].value = curreId;
			// cols[0].displayValue = curreName;
			// pic.resetCols(cols);
			//	// pic.setValue(curreName);
			//}
			pic.open();
			Order.delId = "";
			Order.delName ="";
		},
		cancelAddress:function(data){
			$("input[name='sendCompany']").val('');
		},
		disableClick:function(obj,bool){
			//obj.prop('disabled',bool);
			if("true"==bool){
				obj.attr('disabled',bool);
			} else {
				obj.removeAttr("disabled");
			}
		},
		/**
		 * 保存数据
		 */
		saveData:function(){
			//添加默认数据
			var o = this,params = $("#orderForm").serializeArray();
			var values = {},vali = true;
			for(var p in params ){
				var name = params[p].name;
				var value = params[p].value;
				var title = $("input[name="+name+"]").parent().find("span").text();
				if(value && value!=""){
					// 校验数据有效性
					var validator = $("input[name="+name+"]").attr("check");
					if(validator!="" && validator!=undefined){
						if(validator=="isNotNull" && com.isNull(value)){
							o.showAlert(title+"不能为空");
							return ;
						} else if(validator!="isNotNull"){
							var pattern = o.valids[validator];
							if(validator == "telornumber"){
								var pattern1 = o.valids["tel"];
								var pattern2 = o.valids["phone"];
								var telor = null;
								if (value.substring(0, 1) == 1) {
									telor = !pattern1.test(value);
								} else {
									telor = !pattern2.test(value);
								}
								if(telor){
									o.showAlert("请检查"+title+"输入格式是否正确");
									return ;
								}
							} else {
								if(!pattern.test(value)) {
									o.showAlert("请检查"+title+"输入格式是否正确");
									return ;
								}
							}

						}
					}
					// 重量 和件数
					if(name=="goodsNumber" || name == "weight"){
						var nextVal = $("input[name="+name+"]").parent().find("input[type=number]").val();
						if(parseInt(nextVal) <= 0){
							this.showAlert(title+'不能为零');
							return false;
						}
					}
					if(name.indexOf("isReceive") >= 0 && $("input[name="+name+"]").val()=="true"){
						var nextVal = $("input[name="+name+"]").parent().find("input[type=text]").val();
						if(nextVal==""){
							this.showAlert(title+'不能为空');
							return false;
						}
					}
					if(name =="wholeOrder" && value =="on"){
						value = "1";
					}
					values[name] = value;
				} else {
					if($("input[name="+name+"]").attr("type")!="checkbox" && name!="id"){
						if( name=="remark" || name =="backPicPath"){
							continue;
						}
						if(com.isNull(value)){
							vali = false;
							o.showAlert( title+'不能为空');
							return false;
						}
					}
				}
			}
			if(vali){
				// 检查是否需要保存为默认
				if(o.sendName != $("input[name='sendName']").val() || o.sendPhone!=$("input[name='sendPhone']").val()) {
					layer.open({
						content: '发件人地址对应的用户或是手机与之前不符是否保存？'
						, btn: ['是', '否']
						, yes: function (index) {
							layer.close(index);
							values['sendIsUse'] = 1;
							saveData('yes');
						},no:function (index) {
							saveData('no');
						}
					});
				} else {
					saveData();
				}

				function saveData(test){
					console.log(test+"增加默认。。。")
					o.formSubmit = false;
					o.disableClick($("#subBtn"),"true");
					o.ajaxRequst(o.basePath+"/saveOrder","post",values,"order");
				}

			}
		},
		showAlert:function(msg,url){
			layer.open({
				anim: 'up'
				,content: msg
				,btn: ['确认'],
				yes: function(index){
					layer.close(index);
					if(url!=undefined){
						window.location.href = url;
					}
				}

			});
		},
		loadSendData:function(data){
			if(data){
				Order.showSelect(data,$("#sendCompany"));
			}
		},
		loadRecAddress:function(key){
			$("input[name='recName']").val(Order.receiveData[key]["name"]);
			$("input[name='recPhone']").val(Order.receiveData[key]["phone"]);
			$("input[name='recAddress']").val(Order.receiveData[key]["address"]);
			$("#receiveAddress").val(Order.receiveData[key]["address"]);
		},
		loadReceiveData:function(data){
			Order.showSelect(data,$(".recName"));
			Order.showSelect(data,$(".recPhone"));
			Order.showSelect(data,$(".receiveAddress"));
		},
		showSelect:function(data,obj){
			var other = {};
			if(data!=null){
				var vals = [],disVals=[];
				$.each(data,function (ind,d) {
					disVals.push(Order.getByClassName(d,obj));
					// 寄件人信息
					if(obj.attr("id")=="sendCompany"){
						vals.push(d.id);
						Order.sendData[d.id]={"id":d.id,"name":d.name,"phone":d.phone};
					}
					// 收件人信息
					if(obj.attr("class").indexOf("recName")!=-1 || obj.attr("class").indexOf("recPhone")!=-1 ||
						obj.attr("class").indexOf("receiveAddress")!=-1 ){
						vals.push(d.id);
						// 如果是编辑则把值填上
						var receiveId = $("#receiveId").val();
						if (receiveId!=undefined && receiveId!='' && d.id==receiveId){
							$("input[name='recName']").val(d.name);
							$("input[name='recPhone']").val(d.phone);
							$("input[name='recAddress']").val(d.address);
							other["id"] = receiveId;
							other["name"] = d.address;
						}
						// 收件人数据
						Order.receiveData[d.id]={"name":d.name,"phone":d.phone,"address":d.address};
					}
				});
				obj.click(function () {
					Order.createPicker($(this),vals,other,disVals);
				});

			}
		},
		getByClassName:function(data,obj){
			var that = this;
			if(obj.attr("class").indexOf("recName")!=-1 ){
				return data.name;
			}  else if(obj.attr("class").indexOf("recPhone")!=-1 ){
				return data.phone;
			} else {
				return data.address;
			}
		},
		/**
		 * 发起ajax请求
		 */
		ajaxRequst:function(url,type,data,func){
			var o = this;
			if(!url || !data){
				return;
			}
			$.ajax({
				url:url,
				headers: {
					"authorization": "eEUDDH8NdlW7kW0ZaVJjHCkY7Die"
				},
				type: type,
				dataType: "json",
				data: data,
//                async: false,
//                contentType:'application/json;charset=UTF-8',
				success: function(data) {
//                	var data = eval("("+data+")");//转换为json对象
					if(data.success){
						if($.isFunction(func)){
							func(data.data);
						} else {
							o.formSubmit = true;
							o.disableClick($("#subBtn"),"false");
							o.showAlert("订单保存成功","toCheckExp");
							o.pics = [];
						}
					} else {
						o.disableClick($("#subBtn"),"false");
						o.showAlert(data.message);
					}
				},
				error: function() {
					layer.open({content:'数据出现问题,请重试',btn: ['确认'],
						yes: function(index){
							layer.close(index);
							o.disableClick($("#subBtn"),"false");
						}
					});
				}
			});
//        	return false; // 阻止表单自动提交事件
		},
		initUploader:function(){
			var that = this;
			that = easyUploader({
			id: "uploader",
			accept: '.jpg,.png,.doc,.docx',
			action: 'upFile',
			delAction: 'delFile',
			downAction: 'export',
			dataFormat: 'formData',
			maxCount: 5,
			maxSize: 4,
			multiple: true,
			data: null,
			beforeUpload: function(file, data, args) {
				/* dataFormat为formData时配置发送数据的方式 */
				// data.append('token', '387126b0-7b3e-4a2a-86ad-ae5c5edd0ae6TT');
				// data.append('otherKey', 'otherValue');
				// data.append('url',"");
				/* dataFormat为base64时配置发送数据的方式 */
				// data.base = file.base;
				// data.token = '387126b0-7b3e-4a2a-86ad-ae5c5edd0ae6TT';
				// data.otherKey = 'otherValue';
				console.log(data);
			},
			onChange: function(fileList) {
				/* input选中时触发 */
			},
			onRemove: function(removedFiles, files) {
				console.log('onRemove', removedFiles);
			},
			onSuccess: function(res) {
				console.log('onSuccess', res);
				Order.pics.push(res.data);
				$("#pathPics").val(Order.pics.join(","));
				/**
				 * 注意，接口调通不代表视图会展示成功，接口调通时视图要展示成功需要满足以下两点条件
				 * 1. 返回数据必须由对象包裹，如 { code: 200, data: null }
				 * 2. 必须有一个用于标识成功状态的属性，默认属性是code，默认成功属性值是200，配置项分别对应successKey和successValue，可视情况自行配置
				 */

				/**
				 * 可以在onSuccess/onError等回调函数中通过实例的files属性可以访问上传文件，如 var files = uploader.files; console.log一下就会发现files数组中每个元素由以下属性构成
				 * 1. ajaxResponse: ajax的的响应结果
				 * 2. base: 文件的base64编码
				 * 3. checked: 该文件是否被选中
				 * 4. file: 文件对象
				 * 5. id: 插件内部标识的文件id
				 * 6. isImg: 插件内部标识文件时否是图片
				 * 7. previewBase: 文件压缩后的base64编码，用于插件内部展示预览图
				 * 8. uploadPercentage: 文件上传进度百分比值
				 * 9. uploadStatus: 文件上传状态
				 */
			},
			onError: function(err) {
				Order.pics = [];
				console.log('onError', err);
			},
			})
		},
		init:function(){
			this.bindClick();
			//this.initUploader();
		}
	};
	Order.init();
})